package com.jams.goodox.activity.parent;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.qa.entity.CourseComment;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.activity.qa.teacher.QuestionAnswerDetailActivity;
import com.jams.goodox.activity.qa.teacher.TeacherAnswerActivity;
import com.jams.goodox.activity.qa.teacher.TeacherDetailActivity;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.TimeUtils;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import butterknife.Bind;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by HP on 2018/8/9.
 * 家长问题详情
 */

public class ParentQuestionAnswerDetailActivity extends BaseActivity {
    private static final String TAG = ParentQuestionAnswerDetailActivity.class.getSimpleName();

    private boolean isAnswer;

    @Bind(R.id.image)
    SimpleDraweeView image;
    @Bind(R.id.nickname)
    TextView nickname;
    @Bind(R.id.descr)
    TextView descr;
    @Bind(R.id.time)
    TextView time;


    @Bind(R.id.teacherImage)
    SimpleDraweeView teacherImage;
    @Bind(R.id.teacherName)
    TextView teacherName;
    @Bind(R.id.teacherDesc)
    TextView teacherDesc;

    @Bind(R.id.answer_layout)
    LinearLayout answer_layout;

    @Bind(R.id.answerdetail)
    TextView answerdetail;

    @Bind(R.id.check_answer)
    TextView check_answer;

    @Bind(R.id.teacherPage)
    TextView teacherPage;

    @Bind(R.id.teacherHome)
    RelativeLayout teacherHome;

    private Question question;
    private boolean isBuy = false;
    private int yangCoin;

    private int teacherId;

//    Handler handler = new Handler() {
//        @Override
//        public void dispatchMessage(Message msg) {
//            if (msg.what == 1) {
//                if (isRefresh) {
//                    recyclerView.stopRefresh(status);
//                    pAdapter.notifyDataSetChanged();
//                } else {
//                    recyclerView.stopLoadMore();
//                    pAdapter.notifyDataSetChanged();
//                }
//            }
//        }
//    };

    @Override
    protected int getLayoutId() {
        return R.layout.parentandetail_activity;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, "问题详情");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部
        question = (Question) getIntent().getSerializableExtra("question");
        //问答状态(0未回答，1已回答，2 所有)

        image.setImageURI(SePref.getHeadImageUrl());
        nickname.setText(SePref.getNickName());

        if(null != question){
            isAnswer = (question.getQueState()==1);

            teacherImage.setImageURI(question.getImgPath());
            teacherName.setText(question.getNickName() + (isAnswer ?"  已回答":"  未回答"));
            teacherDesc.setText(question.getIndividualitySign());

            time.setText(TimeUtils.getDateToString(question.getCreateTime()));
            descr.setText(question.getDescr());

        }else {
            isAnswer = false;
            return;
        }

        teacherPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ParentQuestionAnswerDetailActivity.this,
                        TeacherDetailActivity.class);
                intent.putExtra("teacherId",teacherId);
                startActivity(intent);
            }
        });


        check_answer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(SePref.isLogin()){
                    if(yangCoin >= 0){
                        if(SePref.getCoinCount() >= yangCoin){
                            payAnswer();
                        }else {
                            ToastUtil.show("氧币不足，请先充值!");
                        }
                    }
                }else {
                    ToastUtil.show("请先登录!");
                }

            }
        });

        setUI();

        if(SePref.isLogin()){
            getQuestionDetail();
        }else {
            showAnswer();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(SePref.isLogin()){
            teacherHome.setVisibility(View.VISIBLE);
        }else {
            teacherHome.setVisibility(View.GONE);
        }

//        if(isAnswer){
//            getQuestionDetail();
//        }
    }


    //获取详情 判断是否已经购买
    private void getQuestionDetail(){
        clearMap();

        params.put("requestData", "{" +
                "questionId:" + question.getId() +

                ",memberId:" + SePref.getId()

                + "}");
        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).questionDetail(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "getQuestionDetai data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));
                        JSONObject object2 = new JSONObject(object.getString("question"));
                        String title_tx = object2.getString("title");
                        String descr_tx = object2.getString("descr");

                        teacherId = object2.getInt("teacherId");
                        isBuy = object.getBoolean("isPay");
                        if(isAnswer){
                            showAnswer();
                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                //Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }

    //获取问题回答
    private void showAnswer() {
        clearMap();

        params.put("requestData", "{" + "questionId:" + question.getId() + "}");
        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).showAnswer(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "showAnswer data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        JSONObject object = new JSONObject(jsonObject.getString("responseData"));

                        yangCoin = object.getInt("yangCoin");

                        check_answer.setText(yangCoin + "氧币查看答案");

                        answerdetail.setText(object.getString("content"));
                        setUI();


                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }


    private void setUI(){
       /* if(isAnswer && isBuy){
            check_answer.setVisibility(View.GONE);
            answer_layout.setVisibility(View.VISIBLE);

        }else {
            check_answer.setVisibility(View.VISIBLE);
            answer_layout.setVisibility(View.GONE);
        }*/

        if(!isAnswer){
            check_answer.setVisibility(View.GONE);
            answer_layout.setVisibility(View.GONE);
        }else {
            if(isBuy){
                check_answer.setVisibility(View.GONE);
                answer_layout.setVisibility(View.VISIBLE);
            }else {
                if(yangCoin <= 0){
                    check_answer.setVisibility(View.GONE);
                    answer_layout.setVisibility(View.VISIBLE);
                }else {
                    check_answer.setVisibility(View.VISIBLE);
                    answer_layout.setVisibility(View.GONE);
                }
            }
        }
    }

    //购买
    private void payAnswer() {
        clearMap();

        StringBuilder pData = new StringBuilder();
        pData.append("questionId:" + question.getId())
                .append(",coinCount:" + yangCoin)
                .append(",memberId:" + SePref.getId());

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);
        RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example = createCallService(LoginService.class).payAnswer(body);

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "getQuestionDetai data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){

                        if("true".equals(jsonObject.getString("responseData"))){
                            isBuy = true;
                            setUI();
                        }else {
                            ToastUtil.show("购买失败！" );
                        }

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });
    }

}
